<?php

namespace app\index\controller;

use app\index\common\Auth;
use think\Config;
use think\Request;
use think\View;
use Yansongda\Pay\Pay;
use app\index\common\Rsa;
use Firebase\JWT\JWT;

class Index extends Auth
{

    public function _initialize()
    {
        parent::_initialize();
    }

    public function login(Request $request)
    {
        if ($request->isPost()) {
            $token = $request->post('token', NULL);
            if ($token) {

                $data = json_decode(Rsa::privDecrypt($token), TRUE);

                if ($data['username'] == '123' && $data['password'] == '456') {

                    $key   = config('jwt', NULL);
                    $time  = time();
                    $token = array(
                        "iss" => "http://rosae.vip",
                        "aud" => "rosae",
                        "iat" => $time,
                        "exp" => $time + 86400,
                        "data" => $data
                    );

                    $jwt = JWT::encode($token, $key);

                    return Rsa::publicEncrypt(json_encode([
                        'code' => 200,
                        'msg' => 'success',
                        'data' => $jwt
                    ]));
                }
            }

            return Rsa::publicEncrypt(json_encode([
                'code' => 500,
                'msg' => '验证失败！',
                'data' => ''
            ]));

        } else {
            $view = new View();
            return $view->fetch('login');
        }
    }

    public function index(Request $request)
    {
        if ($request->isPost()) {
            $header = request()->header()['authorization'];
            $jwt = substr($header, 7);
            $key   = config('jwt', NULL);
            $data = JWT::decode($jwt, $key, array('HS256'));
            return Rsa::publicEncrypt(json_encode([
                'code' => 200,
                'msg' => 'success',
                'data' => $data
            ]));
        } else {
            $view = new View();
            return $view->fetch('index');
        }
    }

    public function pay()
    {
        Pay::config(Config::get('pay'));
    }

    public function callback()
    {
        Pay::config(Config::get('pay'));
    }

    public function notify()
    {
        Pay::config(Config::get('pay'));
    }
}
